<template>
  <div class="physical-archive-retrieval">
    <div class="header">
      <h2>纸质档案调取管理</h2>
      <el-button type="primary" @click="showSubmitDialog" v-if="userRole === '普通员工'">
        申请调取纸质档案
      </el-button>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-area">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="选择状态" clearable>
            <el-option label="待审批" value="pending"></el-option>
            <el-option label="已批准" value="approved"></el-option>
            <el-option label="已拒绝" value="rejected"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="搜索">
          <el-input v-model="filterForm.search" placeholder="档案标题、申请原因、申请人" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadRequests">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 申请列表 -->
    <el-table :data="requests" style="width: 100%" v-loading="loading">
      <el-table-column prop="archiveTitle" label="档案标题" width="200"></el-table-column>
      <el-table-column prop="physicalLocation" label="存放位置" width="150"></el-table-column>
      <el-table-column prop="userName" label="申请人" width="100" v-if="userRole === '企业领导'"></el-table-column>
      <el-table-column prop="reason" label="申请原因" show-overflow-tooltip></el-table-column>
      <el-table-column prop="expectedRetrievalTime" label="预期调取时间" width="150">
        <template slot-scope="scope">
          {{ formatDate(scope.row.expectedRetrievalTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="expectedReturnTime" label="预期归还时间" width="150">
        <template slot-scope="scope">
          {{ formatDate(scope.row.expectedReturnTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="approvalStatus" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.approvalStatus)">
            {{ getStatusText(scope.row.approvalStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="retrievalCode" label="调取码" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.retrievalCode">{{ scope.row.retrievalCode }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="调取状态" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.actualReturnTime" type="info">已归还</el-tag>
          <el-tag v-else-if="scope.row.isRetrieved" type="warning">已调取</el-tag>
          <el-tag v-else-if="scope.row.approvalStatus === 'approved'" type="success">待调取</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template slot-scope="scope">
          <el-button size="mini" @click="viewDetail(scope.row)">查看详情</el-button>
          
          <!-- 企业领导审批按钮 -->
          <el-button size="mini" type="primary" @click="approveRequest(scope.row)" 
                     v-if="userRole === '企业领导' && scope.row.approvalStatus === 'pending'">
            审批
          </el-button>
          
          <!-- 普通员工确认调取按钮 -->
          <el-button size="mini" type="success" @click="confirmRetrieval(scope.row.requestId)" 
                     v-if="userRole === '普通员工' && scope.row.approvalStatus === 'approved' && !scope.row.isRetrieved">
            确认调取
          </el-button>
          
          <!-- 普通员工确认归还按钮 -->
          <el-button size="mini" type="warning" @click="confirmReturn(scope.row.requestId)" 
                     v-if="userRole === '普通员工' && scope.row.isRetrieved && !scope.row.actualReturnTime">
            确认归还
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="total, prev, pager, next">
    </el-pagination>

    <!-- 提交申请对话框 -->
    <el-dialog title="申请调取纸质档案" :visible.sync="submitDialogVisible" width="600px">
      <el-form :model="requestForm" :rules="requestRules" ref="requestForm">
        <el-form-item label="选择档案" prop="archiveId">
          <el-select v-model="requestForm.archiveId" placeholder="请选择要调取的档案" filterable>
            <el-option 
              v-for="archive in availableArchives" 
              :key="archive.archiveId" 
              :label="archive.title + ' (' + archive.physicalLocation + ')'" 
              :value="archive.archiveId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请原因" prop="reason">
          <el-input type="textarea" :rows="4" v-model="requestForm.reason" placeholder="请说明调取原因"></el-input>
        </el-form-item>
        <el-form-item label="预期调取时间" prop="expectedRetrievalTime">
          <el-date-picker
            v-model="requestForm.expectedRetrievalTime"
            type="datetime"
            placeholder="选择预期调取时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预期归还时间" prop="expectedReturnTime">
          <el-date-picker
            v-model="requestForm.expectedReturnTime"
            type="datetime"
            placeholder="选择预期归还时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="submitDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRequest">提交申请</el-button>
      </div>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog title="审批申请" :visible.sync="approvalDialogVisible" width="500px">
      <el-form :model="approvalForm" ref="approvalForm">
        <el-form-item label="审批结果" prop="status">
          <el-radio-group v-model="approvalForm.status">
            <el-radio label="approved">批准</el-radio>
            <el-radio label="rejected">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批备注">
          <el-input type="textarea" :rows="4" v-model="approvalForm.notes" placeholder="请输入审批备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="approvalDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApproval">确认审批</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="申请详情" :visible.sync="detailDialogVisible" width="700px">
      <div v-if="currentRequest">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="申请ID">{{ currentRequest.requestId }}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{ currentRequest.userName }}</el-descriptions-item>
          <el-descriptions-item label="档案标题">{{ currentRequest.archiveTitle }}</el-descriptions-item>
          <el-descriptions-item label="存放位置">{{ currentRequest.physicalLocation }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ formatDate(currentRequest.requestTime) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentRequest.approvalStatus)">
              {{ getStatusText(currentRequest.approvalStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预期调取时间">{{ formatDate(currentRequest.expectedRetrievalTime) }}</el-descriptions-item>
          <el-descriptions-item label="预期归还时间">{{ formatDate(currentRequest.expectedReturnTime) }}</el-descriptions-item>
          <el-descriptions-item label="调取码" v-if="currentRequest.retrievalCode">{{ currentRequest.retrievalCode }}</el-descriptions-item>
          <el-descriptions-item label="实际调取时间" v-if="currentRequest.actualRetrievalTime">{{ formatDate(currentRequest.actualRetrievalTime) }}</el-descriptions-item>
          <el-descriptions-item label="实际归还时间" v-if="currentRequest.actualReturnTime">{{ formatDate(currentRequest.actualReturnTime) }}</el-descriptions-item>
          <el-descriptions-item label="审批人" v-if="currentRequest.approverName">{{ currentRequest.approverName }}</el-descriptions-item>
          <el-descriptions-item label="审批时间" v-if="currentRequest.approvalTime">{{ formatDate(currentRequest.approvalTime) }}</el-descriptions-item>
          <el-descriptions-item label="申请原因" span="2">{{ currentRequest.reason }}</el-descriptions-item>
          <el-descriptions-item label="审批备注" span="2" v-if="currentRequest.notes">{{ currentRequest.notes }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import service from '@/utils/request'

export default {
  name: 'PhysicalArchiveRetrieval',
  data() {
    return {
      requests: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      userRole: '',
      userId: 0,
      
      filterForm: {
        status: '',
        search: ''
      },
      
      submitDialogVisible: false,
      approvalDialogVisible: false,
      detailDialogVisible: false,
      
      currentRequest: null,
      currentApprovalRequest: null,
      availableArchives: [],
      
      requestForm: {
        archiveId: '',
        reason: '',
        expectedRetrievalTime: '',
        expectedReturnTime: ''
      },
      
      requestRules: {
        archiveId: [
          { required: true, message: '请选择档案', trigger: 'change' }
        ],
        reason: [
          { required: true, message: '请输入申请原因', trigger: 'blur' }
        ],
        expectedRetrievalTime: [
          { required: true, message: '请选择预期调取时间', trigger: 'change' }
        ],
        expectedReturnTime: [
          { required: true, message: '请选择预期归还时间', trigger: 'change' }
        ]
      },
      
      approvalForm: {
        status: 'approved',
        notes: ''
      }
    }
  },
  created() {
    // 从localStorage中获取用户信息
    const user = JSON.parse(localStorage.getItem('user') || '{}');
    this.userRole = user.role || '';
    this.userId = user.userId || 0;
  },
  mounted() {
    this.loadRequests()
    if (this.userRole === '普通员工') {
      this.loadAvailableArchives()
    }
  },
  methods: {
    async loadRequests() {
      this.loading = true
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          status: this.filterForm.status,
          search: this.filterForm.search
        }
        
        const response = await service.get('/api/physical-archive-retrieval/list', { params })
        if (response.data.code === 200) {
          this.requests = response.data.data.records
          this.total = response.data.data.total
        }
      } catch (error) {
        this.$message.error('加载申请列表失败')
      }
      this.loading = false
    },
    
    async loadAvailableArchives() {
      try {
        // 获取有物理位置的档案（表明是纸质档案）
        const response = await service.get('/api/archives/list', {
          params: { pageNum: 1, pageSize: 1000 }
        })
        
        if (response.data.code === 200) {
          this.availableArchives = response.data.data.records.filter(archive => 
            archive.physicalLocation && archive.physicalLocation.trim() !== ''
          )
        }
      } catch (error) {
        this.$message.error('加载档案列表失败')
      }
    },
    
    showSubmitDialog() {
      this.submitDialogVisible = true
      this.requestForm = {
        archiveId: '',
        reason: '',
        expectedRetrievalTime: '',
        expectedReturnTime: ''
      }
    },
    
    async submitRequest() {
      this.$refs.requestForm.validate(async (valid) => {
        if (valid) {
          try {
            const response = await service.post('/api/physical-archive-retrieval/submit', this.requestForm)
            if (response.data.code === 200) {
              this.$message.success('申请提交成功')
              this.submitDialogVisible = false
              this.loadRequests()
            } else {
              this.$message.error(response.data.message)
            }
          } catch (error) {
            this.$message.error('提交申请失败')
          }
        }
      })
    },
    
    approveRequest(request) {
      this.currentApprovalRequest = request
      this.approvalForm = {
        status: 'approved',
        notes: ''
      }
      this.approvalDialogVisible = true
    },
    
    async submitApproval() {
      try {
        const response = await service.put(
          `/api/physical-archive-retrieval/approve/${this.currentApprovalRequest.requestId}`,
          null,
          {
            params: {
              status: this.approvalForm.status,
              notes: this.approvalForm.notes
            }
          }
        )
        
        if (response.data.code === 200) {
          this.$message.success('审批完成')
          this.approvalDialogVisible = false
          this.loadRequests()
        } else {
          this.$message.error(response.data.message)
        }
      } catch (error) {
        this.$message.error('审批失败')
      }
    },
    
    async confirmRetrieval(requestId) {
      this.$confirm('确认您已调取该档案？', '确认调取', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(async () => {
        try {
          const response = await service.put(`/api/physical-archive-retrieval/confirm-retrieval/${requestId}`)
          if (response.data.code === 200) {
            this.$message.success('调取确认成功')
            this.loadRequests()
          } else {
            this.$message.error(response.data.message)
          }
        } catch (error) {
          this.$message.error('确认失败')
        }
      })
    },
    
    async confirmReturn(requestId) {
      this.$confirm('确认您已归还该档案？', '确认归还', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await service.put(`/api/physical-archive-retrieval/confirm-return/${requestId}`)
          if (response.data.code === 200) {
            this.$message.success('归还确认成功')
            this.loadRequests()
          } else {
            this.$message.error(response.data.message)
          }
        } catch (error) {
          this.$message.error('确认失败')
        }
      })
    },
    
    viewDetail(request) {
      this.currentRequest = request
      this.detailDialogVisible = true
    },
    
    resetFilter() {
      this.filterForm = {
        status: '',
        search: ''
      }
      this.currentPage = 1
      this.loadRequests()
    },
    
    handleCurrentChange(page) {
      this.currentPage = page
      this.loadRequests()
    },
    
    formatDate(dateStr) {
      if (!dateStr) return ''
      return new Date(dateStr).toLocaleString()
    },
    
    getStatusType(status) {
      const typeMap = {
        'pending': 'warning',
        'approved': 'success',
        'rejected': 'danger'
      }
      return typeMap[status] || 'info'
    },
    
    getStatusText(status) {
      const textMap = {
        'pending': '待审批',
        'approved': '已批准',
        'rejected': '已拒绝'
      }
      return textMap[status] || status
    }
  }
}
</script>

<style scoped>
.physical-archive-retrieval {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-area {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}

.el-select {
  width: 100%;
}
</style> 